if not pattern then pattern = {} end

if not pattern.imp then

dofile (ScriptsRootPath .. "lib\\lib.lua")

pattern.imp = {}

pattern.imp.patterns_init = lib.path.init .. "patterns.ini"

function pattern.imp.OnCandle(source, index, data)
	if not source then return end
	if not pattern.imp.params then
		pattern.imp.params = lib:LoadIni(pattern.imp.patterns_init, "imp", {
			gap_limit = 0.4,		-- of candle body
			min_size = 1.4			-- of ATR
		})
		if processor and processor.log then
			processor:log("pattern.imp.params", pattern.imp.params)
		end
	end
	
	if not index then index = 1 end
	
	local after = lib:GetLastCandle(source, index)
	local candle = lib:GetLastCandle(source, index + 1)
	local before = lib:GetLastCandle(source, index + 2)
	
	if not (candle and candle.instrument and before and after) then return end
	
	local size_limit = math.max(before.high - before.low, after.high - after.low)
	local candle_size = candle.close - candle.open
	local gap = before.low - after.high
	if candle_size >= 0 then gap = after.low - before.high end
	local vol = ATR(source, index + 1)
	
	if math.abs(candle_size) < pattern.imp.params.min_size * vol or gap <= pattern.imp.params.gap_limit * math.abs(candle_size) then return end
	
	local price = candle.low
	if candle_size >= 0 then price = candle.high end
	
	candle.datetime.is_long__ = candle_size >= 0
	candle.datetime.hint__ = lib:FormatPrice(price, candle.instrument)
			
	candle.datetime.notify__ = string.format("%s IMP %s",
		candle.instrument.code,
		lib:FormatPrice(price, candle.instrument)
	)
	
	return price, candle.datetime
end

function TR(source, index) --True Range ("TR")
	local candle1 = lib:GetLastCandle(source, index)
	local candle2 = lib:GetLastCandle(source, index + 1)
	if candle1 and candle2 then
		return math.max(candle1.high - candle1.low, 
			math.abs(candle1.high - candle2.close), 
			math.abs(candle1.low - candle2.close))
	end
	return nil
end

function ATR(source, index) --Average True Range ("ATR")
	local period = 14
	local ret = 0
	local r
	for i = 0, period - 1 do
		r = TR(source, index + i)
		if not r then
			period = i
			break
		end
		ret = ret + r
	end
	if period > 0 then
		ret = ret / period
	end
	return ret
end

end -- of file
